package com.metaera.app.controller.presenter;

import com.metaera.app.controller.core.SimplePaginationPresenter;
import com.metaera.app.data.DataRepository;
import com.metaera.app.data.model.ArticleListResponse;
import com.metaera.app.data.model.BasicListResponse;
import com.metaera.app.utils.DateUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observable;

public class CalendarItemListPresenter extends SimplePaginationPresenter<ArticleListResponse> {

    private final int mCategoryID;

    private String mCalendar;

    private int currentTimestamp = 0;

    public CalendarItemListPresenter(int categoryID) {
        mCategoryID = categoryID;
        mCalendar = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Calendar.getInstance().getTime());
    }

    public void setParamsAndExecute(String calendar) {
        mCalendar = calendar;
        requestRefresh();
    }

    @Override
    protected Observable<BasicListResponse<ArticleListResponse>> execute() {
        return DataRepository.getInstance()
                .appointDateCalendar(mCalendar, mCategoryID)
                .map(response -> {

                    BasicListResponse.PageDataEntity<ArticleListResponse> data = response.getData();
                    if (data == null) {
                        return response;
                    }

                    List<ArticleListResponse> list = data.getList();
                    if (list == null) {
                        return response;
                    }

                    List<ArticleListResponse> newList = new ArrayList<>();
                    for (ArticleListResponse item : list) {
                        Integer nextTimestamp = item.getRelease_time_stamp();
                        if (!DateUtils.isSameDate(currentTimestamp, nextTimestamp)) {
                            currentTimestamp = nextTimestamp;
                            ArticleListResponse e = new ArticleListResponse();
                            e.setItemType(ArticleListResponse.DATE_TYPE);
                            e.setRelease_time_stamp(nextTimestamp);
                            newList.add(e);
                        }

                        newList.add(item);
                    }

                    data.setItems(newList);

                    return response;
                });
    }

}
